/* eslint-disable eslint-comments/no-unlimited-disable */
// 给地图实例mapInstance增加事件处理的相关方法
/* eslint-disable */
export function Eventify(instance: any) {
  let eventMap: any = {}
  instance.on = function(eventName: string, listen: any) {
    (eventMap[eventName] = eventMap[eventName] || []).push(listen)
    return instance
  }
  instance.once = function(eventName: string, onceListen: any) {
    function listen(...args: any) {
      onceListen.apply(instance.off(eventName, listen), args)
    }
    listen.h = onceListen
    return instance.on(eventName, listen)
  }
  instance.off = function(eventName: string, listen: any) {
    // eslint-disable-next-line no-unmodified-loop-condition
    for (let listens = eventMap[eventName], i = 0; listen && listens && listens[i]; i++)
      listens[i] !== listen && listens[i].h !== listen || listens.splice(i--, 1);

    if (eventMap[eventName].length === 0)
      delete eventMap[eventName]

    return instance
  }
  instance.emit = function(eventName: string) {
    for (let listens = eventMap[eventName], i = 0; listens && listens[i];)
      listens[i++].apply(instance, listens.slice.call(arguments, 1))
    return instance
  }
  instance.clearAllEvents = function() {
    eventMap = {}
  }
  return instance
}
